package teacher;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.*;

// 根据评分数据得到最火的三部电影（评论次数最多的），输出格式：电影编号,评论次数
public class ScoreTest {

    public static class ScoreTestMapper extends Mapper<LongWritable, Text, IntWritable, Text> {

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            // 输出原始行数据，方便调试（在实际应用中，通常不需要这行代码）
            System.out.println(line);

            String[] split = line.split("::");
            int movieId = Integer.parseInt(split[1]); // 假设电影编号在split[1]位置，原代码有误
            String str = split[0] + "," + split[2]; // 拼接用户ID和评分（这里假设split[2]是评分，但通常评分可能是一个单独的字段）

            // 注意：这里的逻辑可能需要根据实际数据文件格式进行调整
            // 例如，如果split[2]不是评分，而是其他信息，则需要相应修改

            context.write(new IntWritable(movieId), new Text(str));
        }
    }

    public static class ScoreTestReducer extends Reducer<IntWritable, Text, IntWritable, IntWritable> {

        private Map<Integer, Integer> map = new HashMap<>();

        @Override
        protected void reduce(IntWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (Text value : values) {
                // 对每个电影ID，累加其出现的次数（这里假设每次出现都代表一次评论）
                sum++;
            }
            map.put(key.get(), sum);
        }

        @Override
        protected void cleanup(Context context) throws IOException, InterruptedException {
            Set<Map.Entry<Integer, Integer>> set = map.entrySet();
            ArrayList<Map.Entry<Integer, Integer>> list = new ArrayList<>(set);
            Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
                @Override
                public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                    return o2.getValue().compareTo(o1.getValue()); // 降序排序
                }
            });

            // 输出评论次数最多的三部电影
            for (int i = 0; i < Math.min(list.size(), 3); i++) {
                context.write(new IntWritable(list.get(i).getKey()), new IntWritable(list.get(i).getValue()));
            }
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        //
        Configuration config = new Configuration();
        Job job = Job.getInstance(config);
        job.setJarByClass(ScoreTest.class);
        job.setMapperClass(ScoreTestMapper.class);
        job.setReducerClass(ScoreTestReducer.class);
        job.setMapOutputKeyClass(IntWritable.class);
        job.setMapOutputValueClass(Text.class);
        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(IntWritable.class);

        FileSystem fs = FileSystem.get(config);
        Path inputPath = new Path(Config.RATE_PATH); // 修正了路径中的拼写错误
        Path outputPath = new Path(Config.OUT_PATH[0]);

        if (fs.exists(outputPath)) {
            fs.delete(outputPath, true);
        }

        FileInputFormat.setInputPaths(job, inputPath);
        FileOutputFormat.setOutputPath(job, outputPath);
        boolean isDone = job.waitForCompletion(true);
        System.out.println(isDone ? "执行成功" : "执行失败");
    }
}